package com.example.mysimpleexample.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.mysimpleexample.R;
import com.example.mysimpleexample.adapter.NewsAdapter;
import com.example.mysimpleexample.entity.News;
import com.example.mysimpleexample.util.Constants;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;
import com.xuexiang.xutil.common.CollectionUtils;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SimpleListFragment extends Fragment {
    public static final String KEY_TITLE = "title";
    public static final String TYPE_ID = "typeId";
    private NewsAdapter adapter;
    private RecyclerView recyclerView;
    private RefreshLayout refreshLayout;
    private int page = 1;
    private OkHttpClient okHttpClient = new OkHttpClient();
    public static final String NEWS_LIST_URL = "/news/list?typeId={typeId}&page={page}";
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int what = msg.what;
            List<News> newsList = (List<News>) msg.obj;
            switch (what) {
                case 0x001:
                    if (adapter != null) {
                        adapter.setList(newsList);
                    }
                    break;
                case 0x002:
                    if (adapter != null) {
                        adapter.addData(newsList);
                    }
                    break;
            }
            return true;
        }
    });
    public SimpleListFragment newInstance(String title,int typeId){
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TITLE,title);
        bundle.putInt(TYPE_ID,typeId);
        SimpleListFragment fragment = new SimpleListFragment();
        fragment.setArguments(bundle);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_simple_list,container,false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        if (bundle == null) {
            return;
        }

        int typeId = bundle.getInt(TYPE_ID,0);
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL));
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new NewsAdapter(R.layout.adapter_list_item);
        recyclerView.setAdapter(adapter);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener(){
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                int what = 0x001;
                loadNewsList(typeId,page,what);
                refreshLayout.finishRefresh();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                int what = 0x002;
                loadNewsList(typeId,page,what);
                refreshLayout.finishLoadMore();
            }
        });
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                News news = (News) adapter.getData().get(position);
                Toast.makeText(getContext(),news.getTitle(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void loadNewsList(int typeId,int page,int what){
        String requestUrl = Constants.BASE_URL.concat(NEWS_LIST_URL.replace("{typeId}"
                ,Integer.toString(typeId)).replace("{page}",Integer.toString(page)));
        Request request = new Request.Builder()
                .url(requestUrl)
                .addHeader("app_id",Constants.APP_ID)
                .addHeader("app_secret",Constants.APP_SECRET)
                .build();
        Log.e("url",requestUrl);
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseText = response.body().string();
                    if (responseText != null) {
                        JSONObject jsonObject = JSONObject.parseObject(responseText);
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        if (CollectionUtils.isNotEmpty(jsonArray)) {
                            List<News> newsList = new ArrayList<>();
                            for (Object o : jsonArray) {
                                News news = JSONObject.parseObject(o.toString(),News.class);
                                newsList.add(news);
                            }
                            Message message = Message.obtain();
                            message.what = what;
                            message.obj = newsList;
                            handler.sendMessage(message);
                        }
                    }
                }
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            Bundle bundle = getArguments();
            int typeId = bundle.getInt(TYPE_ID,0);
            loadNewsList(typeId,page,0x001);
            Log.e("e","加载类型：" + typeId);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public void startRefresh(){
        refreshLayout.autoRefresh();
    }
}
